<template>
  <div class="viewport">
    <div class="select_build select_build2" style="width: 305px">
      <span>日期</span
      ><el-date-picker
        v-model="monthValue"
        style="width: 285px"
        value-format="YYYY-MM-DD"
        :clearable="false"
        type="daterange"
        placeholder="选择"
        @change="changeMonth"
      >
      </el-date-picker>
    </div>
    <div
      id="powerConsumption"
      v-show="powerConsumption_show"
      style="width: 100%; height: 1000px"
    ></div>
  </div>
</template>
  <script>
import * as THREE from "three";
import {
  OrbitControls,
  MapControls,
} from "three/examples/jsm/controls/OrbitControls";
import { nextTick, reactive, ref, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../../api/api";
import echartPillar from "../../components/echart_pillar.vue";
import parsing from "../../assets/js/parsing";
import screenfull from "screenfull";
import "echarts/lib/chart/bar";
import "echarts-gl";
var boxMesh, scene, group, renderer, camera, controls;
var projectId = Number(localStorage.getItem("projectId"));
var areaCode = "";
var scene = new THREE.Scene();
var group = new THREE.Group();
var group1 = new THREE.Group();
var group2 = new THREE.Group();
var powerC,
  electropower,
  electricityRest,
  powerCoption,
  electropowerOption,
  electricityRestOption;
let pNumber = 6,
  tNumber = 6;
export default {
  components: { echartPillar },
  data() {
    return {
      boxMeshList: [],
      innerWidth: 700,
      innerHeight: 580,
      containerShow: true,
      showIndex: 0,
      alarmList: [],
      buildList: [],
      buildingList: [],
      floorList: [],
      objbuilding: {},
      AllbuildingList: [],
      building_value1: "",
      building_value2: "",
      building_value3: "",
      building_value4: "",
      monthValue: "",
      d_areaCode: "",
      alarmSum: {},
      residuelist: [],
      electroList: [],
      electro_power_show: true,
      powerConsumption_show: true,
      echartContainer_show: true,
      echartDeviceState_show: true,
      electricityRest_show: true,
      allList: [],
      ElectricitystatisticsList: [],
      editVisible: false,
      alarmAllList: [],
      fullscreenName: "查看全屏",
    };
  },
  mounted() {
    // myChart = this.$echarts.init(
    //   document.getElementById("echartContainer"),
    //   null,
    //   { devicePixelRatio: 2.5 }
    // );
    // echartDevice = this.$echarts.init(
    //   document.getElementById("echartDeviceState"),
    //   null,
    //   { devicePixelRatio: 2.5 }
    // );
    powerC = this.$echarts.init(
      document.getElementById("powerConsumption"),
      null,
      { devicePixelRatio: 2.5 }
    );
    // electricityRest = this.$echarts.init(
    //   document.getElementById("electricityRestid"),
    //   null,
    //   { devicePixelRatio: 2.5 }
    // );
    this.electro_power_show = false;
    this.powerConsumption_show = false;
    this.echartContainer_show = false;
    this.echartDeviceState_show = false;
    this.electricityRest_show = false;
    // 宿舍用电能耗统计
    powerCoption = {
      tooltip: {},
      visualMap: {
        max: 20,
        inRange: {
          color: [
            "#313695",
            "#4575b4",
            "#74add1",
            "#abd9e9",
            "#e0f3f8",
            "#ffffbf",
            "#fee090",
            "#fdae61",
            "#f46d43",
            "#d73027",
            "#a50026",
          ],
        },
      },

      xAxis3D: {
        type: "category",
        data: [],
        axisLabel: {
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
        },
      },
      yAxis3D: {
        type: "category",
        data: [],
        axisLabel: {
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
        },
        // splitLine: { show: false },
      },
      zAxis3D: {
        type: "value",
        // splitLine: { show: false },
      },
      grid3D: {
        boxWidth: 320,
        boxDepth: 220,
        zlevel: -100,
        // splitLine: { show: false },
        viewControl: {
          // projection: 'orthographic'
          distance: 520,
        },
        axisLabel: {
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
        },
        light: {
          main: {
            intensity: 1.2,
            shadow: true,
          },
          ambient: {
            intensity: 0.3,
          },
        },
      },
      formatter: function (params) {
        let yname = powerCoption.yAxis3D.data[params.value[1]];
        let x = powerCoption.xAxis3D.data[params.value[0]];
        var texts = "";
        texts +=
          "房间号：" +
          "</br>" +
          yname +
          "</br>" +
          "x：" +
          x +
          "</br>" +
          "z：" +
          params.value[2];
        return texts;
      },
      series: [
        {
          type: "bar3D",
          data: "",
          shading: "lambert",
          label: {
            fontSize: 16,
            borderWidth: 1,
          },
          emphasis: {
            label: {
              fontSize: 20,
              color: "#900",
            },
            itemStyle: {
              color: "#fff",
            },
          },
        },
      ],
    };

    // 宿舍用电能耗排名
    // electropower = this.$echarts.init(
    //   document.getElementById("electro-power"),
    //   null,
    //   { devicePixelRatio: 2.5 }
    // );
    const data = [];
    for (let i = 0; i < 5; ++i) {
      data.push(Math.round(Math.random() * 200));
    }
    electricityRestOption = {
      grid: {
        x: "1%", //距离左边
        x2: "5%",
        y: "5%", // 上距离
        y2: "0%", // 下距离
        // left:"100%",
        containLabel: true,
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          crossStyle: {
            color: "#999",
          },
        },
      },
      xAxis: {
        max: "dataMax",
        show: false,
      },
      // dataZoom: [
      //   {
      //     //默认为滚动条型数据区域缩放组件
      //     show: true,
      //     zoomLock: true,
      //     orient: "vertical",
      //     start: 60,
      //     end: 0,
      //   },
      // ],
      yAxis: [
        {
          type: "category",
          data: ["A", "B", "C", "D", "E"],
          axisLabel: {
            textStyle: {
              color: "#fff",
              fontSize: 12,
            },
            interval: 0,
            formatter: function (params) {
              var newParamsName = ""; // 最终拼接成的字符串
              var paramsNameNumber = params.length; // 实际标签的个数
              var provideNumber = 6; // 每行能显示的字的个数
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
              /**
               * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
               */
              // 条件等同于rowNumber>1
              if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                for (var p = 0; p < rowNumber; p++) {
                  var tempStr = ""; // 表示每一次截取的字符串
                  var start = p * provideNumber; // 开始截取的位置
                  var end = start + provideNumber; // 结束截取的位置
                  // 此处特殊处理最后一行的索引值
                  if (p == rowNumber - 1) {
                    // 最后一次不换行
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    // 每一次拼接字符串并换行
                    tempStr = params.substring(start, end) + "\n\n";
                  }
                  newParamsName += tempStr; // 最终拼成的字符串
                }
              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params;
              }
              //将最终的字符串返回
              return newParamsName;
            },
          },
          axisLine: {
            show: false,
          },

          axisTick: {
            show: false,
          },

          splitLine: {
            show: false,
          },
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 9, // only the largest 3 bars will be displayed
        },
        {
          type: "category",
          axisLabel: {
            textStyle: {
              color: "#fff",
              fontSize: 10,
            },
          },
          interval: 0,
          //设置柱状图右边参数
          show: true,
          inverse: true,
          data: [], //设置右边值
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 9, // only the largest 3 bars will be displayed
        },
      ],
      formatter: function (params) {
        var texts = "";
        texts +=
          "剩余电量" +
          "<br>" +
          params[0].data.name +
          "<br>" +
          params[0].data.value;
        return texts;
      },
      series: [
        {
          realtimeSort: false,
          showBackground: true,
          name: "剩余电量",
          type: "bar",
          data: data,
          label: {
            show: false,
            position: "right",
            // valueAnimation: true,
          },
          itemStyle: {
            normal: {
              color: "#0d6ece",
              label: {
                show: false, //开启显示
                position: "right",
                textStyle: {
                  //数值样式
                  color: "#fff",
                  fontSize: 10,
                },
              },
            },
          },
        },
      ],
      legend: {
        show: false,
      },
    };
    var that = this;
    setTimeout(function () {
      projectId = Number(localStorage.getItem("projectId"));
      that.getAllbuild();
    }, 50);
    setTimeout(function () {
      console.log(that.$route.query.ismenu);
      if (that.$route.query.ismenu) {
        screenfull.toggle();
      } else {
        screenfull.exit();
      }
      if (that.$route.query.ismenu) {
        that.fullscreenName = "退出全屏";
      } else {
        that.fullscreenName = "查看全屏";
      }
    }, 200);
  },

  methods: {
    getAllbuild() {
      // // 楼栋
      var that = this;
      api
        .getListAPI("backup/indexData?projectId=" + projectId, {})
        .then((res) => {
          if (res.data.code == 1) {
            this.electro_power_show = true;
            this.powerConsumption_show = true;
            this.echartContainer_show = true;
            this.echartDeviceState_show = true;
            this.electricityRest_show = true;
            // 报警列表
            that.alarmList = res.data.data.alarmInfo;
            // 所有的楼栋select
            that.AllbuildingList = res.data.data.buildingList;
            // 报警统计
            that.alarmSum = res.data.data.alarmSum;
            if (res.data.data.buildingList.length > 0) {
              this.building_value1 = this.AllbuildingList[0].areaCode;
              this.building_value2 = this.AllbuildingList[0].areaCode;
              this.building_value3 = this.AllbuildingList[0].areaCode;
              this.building_value4 = this.AllbuildingList[0].areaCode;
              // this.getDormitoryEnergy(this.AllbuildingList[0].areaCode, 1);
              // this.getDormitoryEnergy(this.AllbuildingList[0].areaCode, null);
              let qareaCode = this.AllbuildingList[0].areaCode.substring(0, 6);
              // console.log(parsing.getSevendays());
              // console.log(parsing.GetDateStr(-1));
              this.monthValue = [
                parsing.getSevendays(),
                parsing.GetDateStr(-1),
              ];
              this.getRegionElectricityForChart(
                qareaCode,
                null,
                parsing.getSevendays(),
                parsing.GetDateStr(-1)
              );
            }
          } else {
            ElMessage.error(res.data.message);
          }
        });

      //3d 获取所有楼栋
      api
        .getListAPI(
          "backup/indexData/alarmingBuilding?projectId=" + projectId,
          {}
        )
        .then((res) => {
          if (res.data.code == 1) {
            this.buildList = res.data.data;
            // for (var i = 0; i < res.data.data.length; i++) {
            //   res.data.data[i].regionList = [];
            //   this.getregionList(res.data.data[i].areaCode);
            // }
            // if (res.data.data.length > 0) {
            //   this.getregionList(res.data.data[0].areaCode);
            // }
          }
        });
    },
    getRegionElectricityForChart(
      queryAreaCode,
      querySortElectricity,
      queryStartDate,
      queryEndDate
    ) {
      api
        .postFormAPI("backup/indexData/regionElectricityForChart", {
          queryStartDate: queryStartDate,
          queryEndDate: queryEndDate,
          queryAreaCode: queryAreaCode,
        })
        .then((res) => {
          console.log(res.data.data);
          if (res.data.code == 1) {
            // 用电量统计
            powerCoption.yAxis3D.data = res.data.data.y;
            powerCoption.xAxis3D.data = res.data.data.x;
            powerCoption.visualMap.max = res.data.data.maxValue;
            powerCoption.series[0].data = res.data.data.xyz.map(function (
              item
            ) {
              return {
                value: [item[1], item[0], item[2]],
              };
            });
            powerC.setOption(powerCoption);
            window.addEventListener("resize", function () {
              powerC.resize();
            });
          } else {
            ElMessage.error(res.data.message);
          }
        });
    },

    compare(property) {
      return function (a, b) {
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
      };
    },
    changeMonth(res) {
      console.log(res);
      let queryAreaCode = this.buildList[0].areaCode;
      console.log(queryAreaCode);
      this.getRegionElectricityForChart(queryAreaCode, null, res[0], res[1]);
    },
  },
  setup(prop, context) {
    const name = localStorage.getItem("ms_username");
    const role = name === "admin" ? "超级管理员" : "普通用户";
    const router = useRouter();
    const alarmMgt = () => {
      router.push("/alarmMgt");
    };
    const handlebuilding = (roomNum, alarmingNum) => {
      if (alarmingNum > 0) {
        router.push("/alarmMgt?roomNum=" + roomNum + "&areaCode=" + areaCode);
      }
    };
    // 查看更多
    const handleMore = () => {
      router.push("/alarmMgt");
    };
    // onBeforeUnmount(() => {
    //   router.go("0");
    // });
    return {
      name,
      role,
      alarmMgt,
      value: "",
      listb: [
        {
          imgsrc:
            "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
        },
        {
          imgsrc:
            "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
        },
      ],
      handlebuilding,
      handleMore,
    };
  },
};
</script>
  <style lang="less" scoped>
@import "../../assets/css/index.css";
@import "../../assets/css/icono.min.css";
@import "../../assets/css/style.css";
@import "../../assets/css/home.less";
@import "../../assets/css/common.css";
&:deep(.content) {
  padding: 0 !important;
}
.monitor {
  margin-left: 10px;
}
#tag {
  z-index: 99999;
  position: absolute;
  // width: 380px;
  max-height: 380px;
  overflow: auto;
  padding: 10px;
  color: #fff;
  background: rgba(86, 122, 165, 0.438);
}
.Allfloor {
  z-index: 99999;
  position: absolute;
  width: 35%;
  height: 60%;
  overflow: auto;
  padding: 10px;
  color: #fff;
  background: rgba(86, 111, 165, 0.438);
  cursor: pointer;
}
.roomList {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.roomList > div:hover {
  background: rgba(192, 191, 191, 0.445);
}
.building_name {
  background: #0c95d6;
  // width: 80px;
  padding: 5px 10px;
  text-align: center;
  margin: 10px 0px 10px 10px;
  // cursor: pointer;
}
.building_name1 {
  background: #c44ec5;
  // width: 80px;
  padding: 5px 10px;
  text-align: center;
  margin: 10px 0px 10px 10px;
  cursor: pointer;
}
.building_name2 {
  background: rgba(192, 191, 191, 0.445);
  // width: 80px;
  padding: 5px 10px;
  text-align: center;
  margin: 10px 0px 10px 10px;
  cursor: pointer;
}
.todayA_cont {
  width: 70px;
}
.more {
  height: 30px;
  width: 100%;
  background: rgba(22, 57, 212, 0.39);
  color: #fff;
  font-size: 0.8rem;
  text-align: center;
  line-height: 30px;
}
&:deep(.el-input__inner) {
  color: #fff;
  height: 40px;
  width: 115px;
}
.category_info {
  color: #fff;
  font-size: 14px;
  // padding-top: 10px;
}
.category_info1 {
  width: 100%;
  color: #fff;
  font-size: 14px;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
  position: relative;
  right: 10px;
}
// #electricityRestid{
//   overflow-y:auto;
// }
// #electro-power {
//   // top: 30px;
// }
#container {
  width: 100%;
  height: 100%;
}
&:deep(.el-input--small .el-input__icon) {
  line-height: 42px;
}
.fullScreen {
  position: absolute;
  // top: 80px;
  // left: 70px;
  right: 30px;
  z-index: 99999;
}
&:deep(.el-select-dropdown__item) {
  padding: 0 10px !important;
}
&:deep(.el-date-editor .el-range-input) {
  color: #fff;
  background: none;
}
.select_build {
  display: flex;
  align-items: center;
  position: absolute;
  width: 100%;
  left: 38%;
  top: 20px;
  z-index: 999999;
  color: #fff;
}
.select_build span {
  width: 80px;
}
</style>
  